#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import os
import json

import fce_util.libs.localrun as localrun
import fce_util.libs.common as common
import fce_util.libs.constants as constants
from fce_util.libs import log as loggers
from fce_util.fceres import fce_res_common

logger = loggers.g_logger.logger

def _package_download_and_deploy(type, pkg_path, install_path, tools):
    if not common.is_dir_exists(pkg_path):
        logger.error('pkg_path %s invalid!' % pkg_path)
        return False, 'package path invalid'

    if not common.is_dir_exists(install_path):
        logger.error('install_path %s not exist, creating..' % install_path)
        localrun.run("mkdir -p " + install_path)
    
    if type == 'local':
        os.chdir(pkg_path)
        for root, dirs, files in os.walk(pkg_path):
            for file in files:
                # 检查文件是否为.tar文件
                if file.endswith(".tar") or file.endswith(".tar.gz") or file.endswith(".tgz"):
                    tar_file_path = os.path.join(root, file)
                    logger.debug('file: %s cmd: %s' % (file,  "tar -zxvf " + tar_file_path + " -C " + root))
                    localrun.run("tar -zxvf " + tar_file_path + " -C " + root)
        
        for tool in tools:
            logger.debug('tool: %s current path: %s' % (tool,  os.getcwd()))
            cmd_prefix = "cp -f "
            if tool == 'operator':
                cmd_prefix = "cp -rf "
                tool = "kuberay-operator"
                install_path = constants.FCE_HOME
            if tool == 'helm':
                tool = "./linux-amd64/helm"
            if tool != 'operator':
                os.chmod(tool, 0o755)
            cmd = '{} {} {}'.format(cmd_prefix, tool, install_path)
            logger.debug('cmd: %s ' % (cmd))
            (status, output) = localrun.run(cmd)
            if status != 0:
                logger.error('package {} install failed, output: {}'.format(tool, output))
                return False, 'package install failed'

    elif type == 'url': #TBD
        (status, output) = localrun.run("curl -s -O " + pkg_path)
        if status != 0:
            logger.error('package install fail, output:%s' % output)
            return False, 'package install fail'
    elif type == 'oss':  #TBD
        logger.warning('install type %s TBD ' % type) #TBD
    else:
        logger.warning('install type %s not support ' % type)
        return False, 'package install fail'

    return  True, "package download and deploy success"

def tools_install(args):
    """
    FCE Util tools install
    """
    
    logger.debug('tools_install enter,args:{}'.format(args))
    
    mode = args.mode if args.mode else 'local'
    pkg_path = args.pkg_path if args.pkg_path else './'
    install_path = args.install_path if args.install_path else './'

    ret, result = _package_download_and_deploy(mode, pkg_path, install_path, constants.FCE_TOOLS)
    if not ret:
        stdout = 'package {} download and deploy failed, output: {}'.format(mode, result)
        logger.error(stdout)
        fce_res_common(success = False, errcode = 'Deploy.ToolInstallFailed', errmsg = stdout)
        return

    msg = {'Success': True}
    msg['Message'] = {
        'Msg': 'tools install success'
    }
    print(json.dumps(msg))

def FCE_tools_install(args):
    if args.deploy == 'tool_install':
        tools_install(args)
        return
    args.this_parser.print_help()

def make(parser):
    """
    FCE Ray Cluster List entry
    """
    parser.add_argument( 
        '--install_path',
        dest='install_path',
        nargs = '?',
        metavar = ('INSTALL_PATH'),
        help='Tools Install Path',
        required=False,
        )   
    
    parser.add_argument( 
        '--pkg_path',
        dest='pkg_path',
        nargs = '?',
        metavar = ('PKG_PATH'),
        help='Tools Package Path',
        required=False,
        )   
    
    parser.add_argument( 
        '--mode',
        dest='mode',
        nargs = '?',
        metavar = ('MODE'),
        help='Tools Install Mode',
        required=True,
        )
    
    parser.set_defaults(
        func=FCE_tools_install,
        this_parser=parser
    )
